package ink.yuanchu.picachoframework.security;

import com.alibaba.fastjson.JSONObject;
import ink.yuanchu.picachoframework.message.Message;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * Created with IntelliJ IDEA.
 *
 * @author ziyuan
 * @Date: 2021/02/20/12:43
 * @Description:
 */
public class JWTAuthenticationEntryPoint implements AuthenticationEntryPoint {

    /**
     * 未登录  即没有token 的情况下
     * httpStatus  401
     * 将错误信息封装成 ant design pro 的json规范  返回
     * 提醒它应该退出登录的状态
     * @param request
     * @param response
     * @param authException
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException, ServletException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/javascript;charset=utf-8");
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.getWriter().print(Message.errorLoginToJson(HttpStatus.UNAUTHORIZED,Message.NO_LOGIN_NO_ACCESS).toString());
    }
}
